package com.atguigu.security.fillter;


import com.alibaba.fastjson2.JSON;
import com.atguigu.common.jwt.JwtHelper;
import com.atguigu.common.result.ResponseUtil;
import com.atguigu.common.result.Result;
import com.atguigu.common.result.ResultCodeEnum;

import com.atguigu.security.config.LoginUserInfoHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 认证解析token过滤器
 * </p>
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 判断是否登录，是登录放行，不是根据token获取权限数据
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        logger.info("uri:" + request.getRequestURI());
        //如果是登录接口，直接放行
        if ("/admin/system/index/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        //获取当前用户信息，并设置到SpringSecurity的登录认证中
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (null != authentication) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.PERMISSION));
        }
    }

    /**
     * 获取用户信息
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // 请求头中获取token
        String token = request.getHeader("token");
        logger.info("token:"+token);
        if (!StringUtils.isEmpty(token)) {
            //解码
            String username = JwtHelper.getUsername(token);
            logger.info("useruame:"+username);
            //判断用户名是否为空
            if (!StringUtils.isEmpty(username)) {
                //将用户id和用户名设置到线程中
                LoginUserInfoHelper.setUserId(JwtHelper.getUserId(token));
                LoginUserInfoHelper.setUsername(username);
                //根据用户名从redis中获取权限数据
                String authoritiesString = (String) redisTemplate.opsForValue().get(username);
                //判断权限数据是否为空
                if (authoritiesString != null)
                System.out.println("+++权限数据JSON+++：" + authoritiesString);//[{"authority":"bnt.sysUser.add"},{"authority":"bnt.sysUser.list"},{"authority":"bnt.sysUser.remove"}]
                //将authoritiesString通过JSON转换成List<Map>
                List<Map> mapList = JSON.parseArray(authoritiesString, Map.class);
                System.out.println("+++权限数据Map+++：" + mapList);//[{authority=bnt.sysUser.add}, {authority=bnt.sysUser.list}, {authority=bnt.sysUser.remove}]

                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    //获取权限数据
                    System.out.println("+++权限数据SimpleGrantedAuthority+++：" + mapList);//
                    authorities.add(new SimpleGrantedAuthority((String)map.get("authority")));
                }
                return new UsernamePasswordAuthenticationToken(username, null, authorities);
            } else {
                return new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
            }
        }
        return null;
    }
}


